import {
  type PayloadAction,
  createSlice,
  createAsyncThunk,
} from "@reduxjs/toolkit";
import { loginApi } from "@/api/login";
import { getPerson } from "@/api/user";
import { deepTree, setRefreshToken, setToken } from "@/utils";

// 登录动作创建函数 定义一个异步动作创建函数
export const login = createAsyncThunk<Login.Resp, Login.Params>(
  "login",
  async (payload) => {
    // 调用登录接口
    const resp = await loginApi(payload);
    // 返回接口返回的数据
    return resp;
  }
);

// 获取用户的动作创建函数
export const person = createAsyncThunk("person", async () => {
  // 调用接口
  const resp = await getPerson();
  // 返回接口返回的数据
  return resp;
});

const userSlice = createSlice({
  name: "user",

  initialState: {
    // 用户token
    token: "",
    // 用户信息
    info: null as User.Info | null,
    // menus 数据，完整的接口返回的 menus
    menus: [] as Menu.Item[],
    // 左侧菜单数据
    menuTree: [] as Menu.Item[],
  },

  reducers: {
    setToken(state, { payload }: PayloadAction<string>) {
      state.token = payload;
    },
  },

  extraReducers: (builder) =>
    builder
      .addCase(login.fulfilled, (state, { payload }) => {
        console.log("login.fulfilled", payload);
        state.token = payload.token;

        // 本地存储 token
        setToken(payload.token);
        // 本地存储 refreshToken
        setRefreshToken(payload.refreshToken);
      })
      .addCase(login.rejected, (state, { payload }) => {
        console.log("login.rejected", payload);
      })
      .addCase(person.fulfilled, (state, { payload }) => {
        state.info = payload.info;
        state.menus = payload.menus;
        // deepTree 算出左侧菜单组件需要的数据
        //    1. payload.menus 移除 type 为 2 的
        const tmp1 = payload.menus.filter((item) => item.type !== 2);
        //    2. 将 tmp1 转换成 tree 格式
        const menuTree = deepTree(tmp1);
        state.menuTree = menuTree;
      }),
});

export default userSlice.reducer;
